<template>
  <div>
    <div>
      <el-descriptions :column="2" direction="vertical">
        <el-descriptions-item width="50%" :label='productInfoTitles.productName'>
          {{ isNullOrEmpty(productInfo?.productName) }}
        </el-descriptions-item>
        <el-descriptions-item width="50%" :label='productInfoTitles.status'>
          <el-tag :type="ENABLE_STATUS[productInfo?.status]?.type">
            {{ isNullOrEmpty(ENABLE_STATUS[productInfo?.status]?.label) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item width="50%" :label='productInfoTitles.accessType'>
          {{ isNullOrEmpty(ACCESS_TYPE[productInfo?.accessType]?.label) }}
        </el-descriptions-item>
        <el-descriptions-item width="50%" :label='productInfoTitles.factoryName'>
          {{ isNullOrEmpty(productInfo?.factoryName) }}
        </el-descriptions-item>
        <el-descriptions-item width="50%" :label='productInfoTitles.remark' :span="2">
          <div style="white-space: pre-wrap;">{{ isNullOrEmpty(productInfo?.remark) }}</div>
          <!-- {{ isNullOrEmpty( productInfo?.remark ) }} -->
        </el-descriptions-item>
      </el-descriptions>
      <div class="absolute right-0 top-0">
        <sj-button custom-type="sinfo" v-auth="'system.product.Update'" @click="editType">编辑</sj-button>
      </div>
    </div>
    <div v-auth="'system.product-model.select'">
      <div>
        <el-button v-auth="'system.product-model.select'" type="primary" :icon="Plus" @click="add">新增产品型号</el-button>
        <!-- <sj-button type="primary" :icon="Plus" @click="add">新增产品型号 </sj-button> -->
        <!-- <el-button type="danger" :icon="Delete" :disabled="!selectionData.length" @click="deletes()">批量删除</el-button> -->
      </div>
      <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)"
        showOverflowTooltip border @selection-change="selectionChange" :isShowPag="false">
        <template #action="{ row }">
          <el-space>
            <!-- <sj-link custom-type="sblue" :underline="false" @click="info(row)">查看</sj-link> -->
            <sj-link custom-type="sblue" :underline="false" @click="edit(row)"
              v-auth="'system.product-model.update'">编辑</sj-link>
            <sj-link custom-type="sred" :underline="false" @click="deletes(row)"
              v-auth="'system.product-model.remove'">删除</sj-link>
          </el-space>
        </template>
      </pure-table>
      <!-- <div class="mt-5">
        <el-pagination v-model:current-page="searchForm.page" v-model:page-size="searchForm.limit" background
          :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
      </div> -->
    </div>
  </div>
</template>
<script lang="ts" setup>
import { isNullOrEmpty, initPureTableConfig } from '@/utils/functions'
import RePage from "@/components/RePage/index.vue";
import editForm from "./form.vue";
import typeFrom from '../../form.vue'
import infos from "./info.vue";
import { reactive, ref, h } from 'vue';
import { PAGE_LAYOUT } from '@/constant';
import { Plus, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { getList, getInfo, addInfo, editInfo, deleteInfo } from '@/api/manage/product-management/product-type/product-model/index';
import { titles, defaultSearchForm, prompt, defaultInfoForm } from './index';
import { addDialog } from "@/components/ReDialog";
import { cloneDeep, isAllEmpty, deviceDetection, debounce } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customDebounce, customPromiseDebounce } from "@/utils/functions";
import { defaultInfoForm as defaultProductInfo, titles as productInfoTitles } from '../../index';
import { getProductTypeInfo as getTypeInfo, editInfo as editTypeInfo } from '@/api/manage/product-management/product-type/index';

import { ENABLE_STATUS, ACCESS_TYPE } from '@/constant/product-management'
const props = defineProps({
  productInfo: {
    type: Object,
    default: defaultProductInfo()
  }
});
const emits = defineEmits(['editTypes']);
const searchForm = ref(defaultSearchForm());
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const tableData = reactive({
  data: [],
  total: 0,
});

const searchFormRules = [
  { type: 'number', field: 'page', title: 'page', hidden: true },
  { type: 'number', field: 'limit', title: 'limit', hidden: true },
];
const selectionData = ref([]);
const roleTableConfig = [
  // { type: "selection", align: "left" },

  { prop: 'id', width: 60, label: titles.id, fixed: 'left' },
  { prop: 'modelName', label: titles.modelName, minWidth: 100 },
  { prop: 'modelDesc', label: titles.modelDesc, minWidth: 150 },
  { slot: 'action', label: titles.action, width: 100, fixed: 'right' },
];
watch(() => props.productInfo, () => {
  if (props.productInfo?.productId) {
    getTableList();
  }
}, {
  deep: true,
  immediate: true
});
onMounted(() => {
  // getTableList()
});
// 编辑
const editType = () => {
  showInfo.value = {}
  addDialog({
    title: `产品类型修改`,
    width: "1100px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(typeFrom, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        formInline: defaultInfoForm()
      }
      getTypeInfo({ id: props.productInfo?.productId }).then(res => {
        if (res.code == 200) {
          showInfo.value = res.result
          options.props.formInline = res.result
        }
      }).finally(() => {
        options.props.isLoading = false
      })
    },
    beforeSure(done, { options, index }) {
      const formData = options.props.formInline;
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        emits('editTypes')
        done(); // 关闭弹框
        // getTableList(); // 刷新表格数据
      }
      DebounceEditTypeInfo(formData).then(res => {
        if (res.code == 200) {
          chores();
        }
        options.props.isLoading = false;
      }).catch((err) => {
        if (err !== '请求中') {
          options.props.isLoading = false;
        }
      })
    },
  });
}
// 获取列表数据
const getTableList = () => {
  getList({
    productId: props.productInfo.productId
  }).then(res => {
    if (res.code === 200) {
      tableData.data = res.result;
      // tableData.total = res.result.total;
    }
  })
}
// 重置搜索栏
const resetting = () => {//点击重置按键
  Object.assign(searchForm.value, defaultSearchForm())
  key.value++
  getTableList()
}
// 详情
const info = (row) => {
  addDialog({
    title: `详情`,
    hideFooter: true,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(infos, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        formInline: defaultInfoForm()
      }
      getInfo({ id: row.id }).then(res => {
        if (res.code == 200) {
          showInfo.value = res.result
          options.props.formInline = res.result
        }
      }).finally(() => {
        options.props.isLoading = false
      })
    },
  });
}
// 新增
const add = (row) => {
  showInfo.value = {}
  openDialog()
}
// 编辑
const edit = (row) => {
  showInfo.value = {}
  openDialog("编辑产品型号", row)
}
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(
    `确认删除${row ? '当前' : '选中的'}数据?`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteInfo({
        // id: row.id,
        // productId: props.productInfo.productId
        ids: row ? [row.id] : selectionData.value.map(item => item.id)
      }).then(res => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableList();
        }
      })
    })
}
// 开启弹窗
const openDialog = (title = "添加产品型号", row?: any) => {
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(editForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (row) {
        options.props = {
          isLoading: true,
          formInline: defaultInfoForm()
        }
        getInfo({ id: row.id }).then(res => {
          if (res.code == 200) {
            showInfo.value = res.result
            options.props.formInline = res.result
          }
        }).finally(() => {
          options.props.isLoading = false
        })
      } else {
        options.props = {
          isLoading: false,
          formInline: defaultInfoForm()
        }
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      formData.productId = props.productInfo.productId
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "添加产品型号") {
            DebounceAddInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            DebounceEditInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }
        }
      });
    }
  });
}
const selectionChange = data => {
  selectionData.value = data;
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
// 编辑请求
const DebounceEditTypeInfo = customPromiseDebounce(editTypeInfo, 1000, true);

</script>
<style lang="scss" scoped></style>
